package com.example.transformation;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created with IntelliJ IDEA.
 * ClassName: RichFunctionDemo
 * Package: com.example.transformation
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-18
 * Time: 18:41
 */

public class RichFunctionDemo {
    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        env.setParallelism(1);

        DataStreamSource<Integer> source = env.fromElements(1,2,3,4);


        /**
         * RichFunction富函数
         * open() 每个子任务 在启动是调用一次
         * close() 每个子任务在结束时 调用一次
         * 如果是flink程序挂掉了 不会调用close
         * 如果正常调用cancel命令 可以执行close
         *
         * 多了一个运行是上下文件
         * 可以获取运行时候的信息
         */
        SingleOutputStreamOperator<Integer> map = source.map(new RichMapFunction<Integer, Integer>() {

            @Override
            public void open(Configuration parameters) throws Exception {

                super.open(parameters);

                RuntimeContext runtimeContext = getRuntimeContext();
                int indexOfThisSubtask = runtimeContext.getIndexOfThisSubtask();
                String taskNameWithSubtasks = runtimeContext.getTaskNameWithSubtasks();

                System.out.println("子任务编号: " + indexOfThisSubtask);
                System.out.println("启动子任务名称" + taskNameWithSubtasks);
                System.out.println("open调用");
            }

            @Override
            public void close() throws Exception {
                super.close();
                RuntimeContext runtimeContext = getRuntimeContext();
                int indexOfThisSubtask = runtimeContext.getIndexOfThisSubtask();
                String taskNameWithSubtasks = runtimeContext.getTaskNameWithSubtasks();

                System.out.println("子任务编号: " + indexOfThisSubtask);
                System.out.println("启动子任务名称" + taskNameWithSubtasks);
                System.out.println("close调用");
            }

            @Override
            public Integer map(Integer integer) throws Exception {
                return integer + 1;
            }
        });

        map.print();


        env.execute();


    }
}
